﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using AntUnion.FrameWork.Model.Models;
using Util.Extension;
using Microsoft.AspNetCore.Hosting;
using AntUnion.FrameWork.Util;
using Microsoft.AspNetCore.Mvc.Rendering;
using AntUnion.FrameWork.Web.Extend;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class UsersController : BaseController
    {
        private readonly mtContext _context;

        public UsersController(mtContext context, IWebHostEnvironment env) : base(context, env)
        {
            _context = context;
        }

        #region 获取角色下拉列表
        public SelectList GetRolesList(int level)
        {
            level = level + 1;
            SelectList sl = null;
            var data = _context.TbRoles.Where(k => k.Level == level && k.UserType == 0).AsNoTracking().ToList();
            if (data.Count > 0)
            {
                IEnumerable<object> ie = data.AsEnumerable();
                sl = new SelectList(ie, "Id", "Names");
            }
            return sl;
        }
        #endregion

        #region 用户列表
        public IActionResult Index()
        {
            ViewBag.isShow = User.Level == 1;
            return View();
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetListJson(int page, int limit)
        {
            ListResult res = new ListResult();
            try
            {
                var data = from n in UserFilter()
                           select new UserModel
                           {
                               Id = n.Id,
                               Names = n.UserName,
                               Level = n.Level,
                               UserName = n.UserName,
                               LoginName = n.LoginName,
                               UserPwd = n.LoginPwd,
                               LastIp = n.LastIp,
                               LastTime = n.LastTime,
                               Creator = n.Creator,
                               CreateDate = n.CreateDate,
                               State = n.State,
                               Remark = n.Remark,
                               Pid = n.Pid,
                               roles = _context.TbUserRoles.Any(r => r.UserId == n.Id) ? _context.TbRoles.Where(k => k.Id == _context.TbUserRoles.Where(r => r.UserId == n.Id && r.UserType == 0).Select(k => k.RoleId).FirstOrDefault()).Select(k => k.Remark).FirstOrDefault() : "",
                           };
                //var list = data.ToList();


                res.Code = 0;
                res.Count = data.Count();
                res.Data = data.OrderBy(k => k.Id).Skip((page - 1) * limit).Take(limit).ToList(); ;
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
            }
            return new JsonResult(res);
        }
        #endregion

        #region 添加用户

        public IActionResult Create(int level, int pid = 0)
        {
            ViewBag.RolesList = GetRolesList(level);
            TbUser model = new TbUser();
            model.Level = level + 1;
            model.Pid = pid;
            return View(model);
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Create(UserExt item)
        {
            Result res = new Result();
            try
            {
                if (!TbUserExists(item.LoginName))
                {
                    TbUser model = new TbUser();
                    model.UserName = item.UserName;
                    model.LoginName = item.LoginName;
                    model.Remark = item.Remark;
                    model.LoginPwd = SecurityUtil.EncryptPwd(item.UserPwd);
                    model.Creator = User.UserName;
                    model.CreateDate = DateTimeUtil.Now;
                    model.Pid = item.Pid;
                    model.Level = item.Level;
                    model.State = 1;
                    _context.Add(model);
                    _context.SaveChanges();
                    TbUserRole userRole = new TbUserRole
                    {
                        RoleId = item.RoleId,
                        UserId = model.Id,
                        UserType = 0
                    };
                    _context.TbUserRoles.Add(userRole);
                    
                    res.Code = 0;
                    res.Data = await _context.SaveChangesAsync();
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "loginNameExists";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 编辑用户信息
        public async Task<IActionResult> Edit(int? id, int live)
        {
            if (id == null)
            {
                return NotFound();
            }

            TbUser tbUser = await _context.TbUsers.FindAsync(id);
            if (tbUser == null)
            {
                return NotFound();
            }

            return View(tbUser);
        }
        /// <summary>
        /// 编辑用户信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Edit(UserExt item)
        {
            Result res = new Result();
            try
            {
                if (!TbUserExists(item.LoginName, item.Id))
                {
                    TbUser model = await _context.TbUsers.FindAsync(item.Id);
                    if (model != null)
                    {
                        if (!string.IsNullOrEmpty(item.UserPwd))
                            model.LoginPwd = SecurityUtil.EncryptPwd(item.UserPwd);
                        model.UserName = item.UserName;
                        model.LoginName = item.LoginName;
                        model.Remark = item.Remark;
                        
                        res.Code = 0;
                        res.Data = await _context.SaveChangesAsync();
                    }
                    else
                    {
                        res.Code = 1;
                        res.Msg = "用户不存在";
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "登录名已存在";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="intState"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UpdateState(int id, int intState)
        {
            Result res = new Result();
            try
            {
                TbUser tbUser = await _context.TbUsers.FindAsync(id);
                tbUser.State = intState;
                
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 删除用户
        /// <summary>
        /// 删除单个用户
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        [HttpPost, ActionName("Delete")]
        public JsonResult Delete(int id)
        {
            Result res = new Result();
            try
            {
                if (_context.TbUsers.Where(k => k.Pid == id).Any())
                {
                    res.Code = 1;
                    res.Msg = "此用户还有下级用户，不能删除！";
                    return new JsonResult(res);
                }
                TbUser tbUser = _context.TbUsers.Find(id);
                if (tbUser.Id == 1)
                {
                    res.Code = 1;
                    res.Msg = "此管理员不能删除！";
                    return new JsonResult(res);
                }
                _context.TbUsers.Remove(tbUser);
                
                res.Code = 0;
                res.Data = _context.SaveChanges();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids">要删除的用户ID；多个用“,”分开</param>
        /// <returns></returns>
        [HttpPost, ActionName("DeleteItems")]
        public async Task<IActionResult> DeleteItems(string ids)
        {
            Result res = new Result();
            try
            {
                List<int> list = new List<int>();
                string[] idList = ids.Split(',');
                foreach (string id in idList)
                {
                    list.Add(id.ToInt());
                }
                List<TbUser> userList = await _context.TbUsers.Where(k => list.Contains(k.Id)).ToListAsync();
                int num = 0;
                foreach (TbUser model in userList)
                {
                    if (model.Id == 1)
                        continue;
                    if (_context.TbUsers.Where(k => k.Pid == model.Id).Any())
                    {
                        num++;
                        continue;
                    }
                    
                    model.Isdel = 1;
                }
                res.Code = 0;
                res.Msg = $"删除成功{(num > 0 ? "；部分用户还有下级用户，不能删除！" : "！")}";
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 判断是否存在
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="LoginName">登录名称</param>
        /// <param name="id">排除ID</param>
        /// <returns></returns>
        private bool TbUserExists(string LoginName, int id = 0)
        {
            if (id == 0)
                return _context.TbUsers.Any(e => e.LoginName == LoginName);
            else
                return _context.TbUsers.Any(e => e.Id != id && e.LoginName == LoginName);
        }
        #endregion

        #region 实体
        public class UserModel
        {
            public int Id { get; set; }
            public string Names { get; set; }
            public int Level { get; set; }
            public string UserName { get; set; }
            public string LoginName { get; set; }
            public string UserPwd { get; set; }
            public string LastIp { get; set; }
            public DateTime? LastTime { get; set; }
            public string Creator { get; set; }
            public DateTime CreateDate { get; set; }
            public int State { get; set; }
            public string Remark { get; set; }
            public int p { get; set; }
            public int Pid { get; set; }
            public string LimitUrl { get; set; }
            //分享人数
            public int TotalPeople { get; set; }
            //累计充值次数
            public int TotalTimes { get; set; }
            //累计充值金额
            public decimal TotalAmount { get; set; }
            public string roles { get; set; }
        }
        #endregion
    }
}
